<template>
  <div>
    <div style="margin: 10px 0">
      <el-input v-model="username" placeholder="请输入用户名" style="width: 200px" suffix-icon="el-icon-search">
      </el-input>
      <el-input v-model="email" placeholder="请输入邮箱" style="width: 200px;margin-left: 5px"
                suffix-icon="el-icon-message">
      </el-input>
      <el-input v-model="address" placeholder="请输入地址" style="width: 200px;margin-left: 5px"
                suffix-icon="el-icon-location">
      </el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0;">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-plus"></i></el-button>
      <el-popconfirm
          style="margin-left: 10px"
          confirmButtonText="确定"
          cancelButtonText="取消"
          title="确定删除吗？"
          @confirm="handleDeleteAll"
      >
        <el-button type="danger" slot="reference">批量删除
          <i class="el-icon-delete"></i></el-button>
      </el-popconfirm>
      <el-upload
          action="http://localhost:9090/user/importExcel" :show-file-list="false" accept=".xls,.xlsx"
          :on-success="handleImportSuccess"
          style="display: inline-block;margin-left: 10px">
        <el-button type="primary">导入 <i class="el-icon-upload"></i></el-button>
      </el-upload>

      <el-button type="primary" @click="handleExport" class="ml5">导出 <i class="el-icon-download"></i>
      </el-button>
    </div>
    <el-table :data="tableData" border stripe header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="username" label="用户名">
      </el-table-column>
      <el-table-column prop="role" label="角色">
      </el-table-column>
      <el-table-column prop="nickname" label="昵称">
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop="phone" label="电话">
      </el-table-column>
      <el-table-column prop="address" label="地址">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="230">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.$index, scope.row)">编辑<i class="el-icon-edit"></i>
          </el-button>
          <el-popconfirm
              style="margin-left: 10px"
              confirmButtonText="确定"
              cancelButtonText="取消"
              title="确定删除吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button type="danger" slot="reference">删除
              <i class="el-icon-delete"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px" size="small">
        <el-form-item label="用户名">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.flag">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      tableData: [],
      // 用户名
      username: "",
      // 邮箱
      email: "",
      // 地址
      address: "",
      // 表单数据
      form: {},
      // 当前页码
      pageNum: 1,
      // 每页条数
      pageSize: 10,
      // 总条数
      total: 10,
      // 表格选中数据
      multipleSelection: [],
      // 表单数据,是否展示
      dialogFormVisible: false,
      // 菜单样式
      headerBg: 'headerBg',
      // 角色列表
      roleList: []
    }
  },
  methods: {
    load() {
      // 获取用户数据
      request.get("/user/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
          email: this.email,
          address: this.address
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data;
        this.total = res.total;
      })

      // 获取角色列表
      request.get("/role/list").then(res => {
        this.roleList = res.data;
      })
    },
    reset() {
      this.username = "";
      this.email = "";
      this.address = "";
      this.load();
    },
    // 分页
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
    // 分页
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      // 深拷贝,防止和原数据关联导致，修改form数据时候，影响row的数据
      this.form = JSON.parse(JSON.stringify(row));
    },
    // 删除
    handleDelete(index, row) {
      request.delete("/user/" + row.id).then(res => {
        this.load();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    },
    // 批量删除
    handleDeleteAll() {
      let ids = [];
      this.multipleSelection.forEach(item => {
        ids.push(item.id);
      })
      request.post("/user/del/batch", ids).then(res => {
        this.load();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    },
    // 控制新增弹窗
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {
        username: "",
        nickname: "",
        email: "",
        phone: "",
        address: ""
      }
    },
    // 保存
    saveUser() {
      request.post("/user", this.form).then(res => {
        this.dialogFormVisible = false;
        this.load();
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
      })
    },
    // 列表多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 导出Excel表格
    handleExport() {
      // response.setHeader("Content-Disposition", "attachment;filename=" + finalFileName + ".xlsx");
      // 由于后端设置了这个响应头的操作,才实现了导出操作，而不是打开一个新窗口
      // 方式一
      // window.open("http://localhost:9090/user/exportExcel")

      // 方式二
      //   导入功能编写
      request.get("/user/exportExcel", {
        responseType: 'blob'
      }).then(res => {
        console.log(res)
        let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = '用户信息.xlsx';
        document.body.appendChild(downloadElement);
        downloadElement.click();
      })
    },
    // 导入Excel表格成功的钩子函数
    handleImportSuccess() {
      this.load();
      this.$message({
        type: 'success',
        message: '导入成功!'
      });
    }
  },
  mounted() {
    this.load();
  }
}
</script>

<style scoped>
.headerBg {
  background-color: #eeeeee !important;
}
</style>